#ifndef LOGCLASS_H
#define LOGCLASS_H


#include <QObject>
#include <QString>
#include <QDateTime>
#include <QFile>
#include <QTextStream>
#include <QMutex>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlTableModel>
#include <QVector>
#include <QFileInfo>
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include "sqlitemanage.h"

// 日志类型枚举
enum LogType {
    SYSTEM_LOG = 0,
    OPERATION_LOG,
    ALARM_LOG,
    EXCEPTION_LOG
};

// 日志等级枚举
enum LogLevel {
    INFO = 0,
    WARNING,
    ERR,
    CRITICAL
};


// 日志记录单例类
class LogClass : public QObject
{
    Q_OBJECT
public:
    static LogClass* getInstance();
    ~LogClass();

    // 记录日志接口
    void log(SqliteManage *m_pSqliteManage,LogType type, LogLevel level, const QString& content, int userId = -1, int deviceId = -1);
    // 系统日志
    void systemLog(SqliteManage *m_pSqliteManage,LogLevel level, const QString& content);
    // 操作日志
    void operationLog(SqliteManage *m_pSqliteManage,LogLevel level, const QString& content, int userId = -1);
    // 告警日志
    void alarmLog(SqliteManage *m_pSqliteManage,LogLevel level, const QString& content, int deviceId = -1);
    // 异常日志
    void exceptionLog(SqliteManage *m_pSqliteManage,LogLevel level, const QString& content);
    // 查询日志
    QVector<QVector<QVariant>> queryLogs(SqliteManage *m_pSqliteManage,
                                        const QDateTime& startTime,
                                        const QDateTime& endTime,
                                        LogType type = SYSTEM_LOG,
                                        const QString& keyword = "");

    // 导出日志
    bool exportLogs(SqliteManage *m_pSqliteManage,const QString& filePath,
                   const QDateTime& startTime,
                   const QDateTime& endTime,
                   LogType type = SYSTEM_LOG,
                   const QString& keyword = "",
                   bool isCsv = true);

private:
    explicit LogClass(QObject *parent = nullptr);
    LogClass(const LogClass&) = delete;
    LogClass& operator=(const LogClass&) = delete;

    // 初始化数据库
    bool initDatabase();
    // 检查并创建日志表
    bool createLogTable();
    // 检查并轮转日志文件
    void checkAndRotateLogFile();
    // 写入日志到文件
    void writeToFile(const QString& logLine);
    // 获取日志类型字符串
    QString logTypeToString(LogType type) const;
    // 获取日志等级字符串
    QString logLevelToString(LogLevel level) const;
    // 获取当前日志文件路径
    QString getCurrentLogFilePath() const;

private:
    static LogClass* m_instance;
    static QMutex m_mutex;

    QSqlDatabase m_database;
    QString m_logDir;
    QString m_currentLogFile;
    qint64 m_maxLogSize;
};

#endif // LOGCLASS_H
